import React from 'react'
import { connect } from 'react-redux'
import moment from "moment/moment";
import { messages } from 'share/common';
import { Button, message, Icon, Spin } from 'antd';
import 'styles/expense-report/subsidy-content.scss';
import SubsidyMiddle from 'containers/expense-report/template/subsidy-middle';
import subsidyService from "containers/expense-report/template/subsidy-service";
import Skeleton from 'components/skeleton'
import Condition from 'components/condition'
const { If } = Condition;

class SubsidyContent extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      submitLoading: false,
      expenseReportOID: null,
      hasUpdate: false,
      subsidyList: [],
      checkLoading: false,
      subsidyLength: 0,
      editArray: [],
      subsidyRules: []
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.subsidyFrame || !nextProps.loading)
      return;
    this.setState({
      subsidyList: nextProps.subsidyInfo.expenseReportSubsidyViewList || [],
      subsidyLength: (nextProps.subsidyInfo.expenseReportSubsidyViewList || []).length,
      expenseReportOID: nextProps.expenseReportOID,
      hasUpdate: false,
    })
  };

  handleSave = () => {
    const { subsidyInfo } = this.props.params;
    const { subsidyList, expenseReportOID, editArray } = this.state;
    let allTrue = this.verification();
    if (allTrue) {
      let temp = false;
      editArray.map(item => {
        item && (temp = true);
      });
      if (temp) {
        message.error(messages('expense-parent-report.key153')/*请先保存或取消数据的修改！*/);
      } else {
        let copy = JSON.parse(JSON.stringify(subsidyList));
        subsidyList.map(item => {
          item.expenseReportSubsidyDTOS && item.expenseReportSubsidyDTOS.map(record => {
            delete record.edit;
            delete record.idealID;
            delete record.showCancelEdit;
            record.expenseReportOID = expenseReportOID;
            record.subsidyExtendID = item.subsidyExtendID;
          });
          delete item.hasEdit;
        });
        let params = {
          expenseReportSubsidyViewList: subsidyList,
          showExtend: subsidyInfo.showExtend
        };
        this.setState({ submitLoading: true });
        subsidyService.saveDataList(expenseReportOID, params).then(() => {
          this.setState({ submitLoading: false });
          this.props.close(true)
        }).catch(e => {
          this.setState({ submitLoading: false });
          message.error(e.response.data.message)
        })
      }
    }
  };

  verification = () => {
    let { subsidyList } = this.state;
    const { withCity } = this.props.params.subsidyInfo;
    let result = true;
    let errorMessage = [];
    let errorMessageType = []; //为了过滤掉相同的报错
    subsidyList.map(obj => {
      obj.expenseReportSubsidyDTOS.map(item => {
        if (item.edit) {
          item.error = true;
          result = false;
          // 该城市无差补类型 未选择差补类型 统一报错必填信息未填
          if (!((typeof item.international === 'boolean') &&
              ((withCity && item.cityName) || !withCity) &&
              item.startDate && item.endDate &&
              item.expenseTypes && item.expenseTypeOIDs
            ) || item.expenseTypes.length === 0 ||
            item.expenseTypeOIDs.length === 0) {
            if (!~errorMessageType.indexOf(1)) {
              errorMessage.push(messages('expense-parent-report.key67'/*必填信息未填*/));
              errorMessageType.push(1);
            }
          } else if (item.remark && item.remark.length > 200) {
            if (!~errorMessageType.indexOf(2)) {
              errorMessage.push(messages('common.max.characters.length', {max: 200}));
              errorMessageType.push(2);
            }
          } else {
            item.error = false;
            result = true;
          }
        }
      })
    });
    if (errorMessage.length) {
      errorMessage.length === 1 ? message.error(errorMessage[0]) :
        message.error(
          errorMessage.map((item, index) => <p style={{textAlign: 'left', marginLeft: 5}}>{index + 1}: {item} </p>)
        )
    }
    this.setState({ subsidyList });
    return result;
  };

  handleChange = (params) => {
    const { subsidyList } = this.state;
    subsidyList.map((item, index) => {
      if (index === params.index) {
        item.expenseReportSubsidyDTOS = params.dataList;
        params.allObj && (item = params.allObj);
        item.hasEdit = params.hasEdit;
        subsidyList[index] = item;
      }
    });
    this.setState({ subsidyList });
  };

  //添加差旅行程（大行程）
  addSubsidy = () => {
    const { subsidyList, expenseReportOID } = this.state;
    const { expenseInfo } = this.props;
    const { subsidyInfo } = this.props.params;
    let temp = [];
    subsidyList.map(item => {
      if(item.hasEdit){
        delete item.hasEdit;
        item.expenseReportOID = expenseReportOID;
        temp.push(item);
      }
    });
    this.setState({ checkLoading: true });
    subsidyService.checkSubsidy(temp).then(() => {
      this.setState({ checkLoading: false });
      let obj = subsidyList[subsidyList.length - 1];
      let startTime = `${moment(moment(obj.subsidyEndDate).subtract(-1, 'days').format('YYYY-MM-DD 00:00:00')).utc().format('YYYY-MM-DDTHH:mm')}Z`;
      let endTime = `${moment(moment(obj.subsidyEndDate).subtract(-1, 'days').format('YYYY-MM-DD 23:59:59')).utc().format('YYYY-MM-DDTHH:mm')}Z`;
      // 报销单头信息的结束日期【小于等于】当前差补的结束日期
      // 或 报销单头信息结束日期【等于】当前差补结束日期 + 1
      // 新增大行程的日期为头信息结束日期，时间为头信息结束日期的【0点 - 头信息结束时间点】
      let reportEndDateTime = new Date(moment(subsidyInfo.reportEndDate).format('YYYY-MM-DD 00:00:00')).getTime();
      if (
        subsidyInfo.reportEndDate && (
          reportEndDateTime <= new Date(obj.subsidyEndDate).getTime() ||
          reportEndDateTime === new Date(startTime).getTime()
        )
      ) {
        startTime = `${moment(moment(subsidyInfo.reportEndDate).format('YYYY-MM-DD 00:00:00')).utc().format('YYYY-MM-DDTHH:mm')}Z`;
        endTime = `${moment(subsidyInfo.reportEndDate).utc().format('YYYY-MM-DDTHH:mm')}Z`;
      }
      // 将所有大行程下的小行程状态都变为非编辑
      subsidyList.map(item => {
        item.expenseReportSubsidyDTOS.map(record => {
          record.edit = false;
        })
      });
      let newSubsidy = {
        expenseReportSubsidyDTOS: [],
        subsidyStartDate: startTime,
        subsidyEndDate: endTime,
        userDTOList: [{
          id: expenseInfo.applicantID,
          userOID: expenseInfo.applicantOID,
          fullName: expenseInfo.applicantName,
        }]
      };
      subsidyList.push(newSubsidy);
      this.setState({ subsidyList, subsidyLength: subsidyList.length });
    }).catch(e => {
      message.error(e.response.data.message);
      subsidyList.map(item => {
        temp.map(it => {
          if(item.subsidyExtendID === it.subsidyExtendID){
            item.hasEdit = true;
          }
        })
      });
      this.setState({checkLoading: false, subsidyList});
    })
  };

  deleteSubsidy = id => {
    const { subsidyList } = this.state;
    subsidyList.map((item, index) => {
      if (index === id) {
        subsidyList.splice(index, 1);
        this.setState({ subsidyList }, () => {
          this.setState({ subsidyLength: subsidyList.length });
        });
      }
    });
  };

  validateSave = (id,bool) => {
    const {editArray} = this.state;
    editArray[id] = bool;
    this.setState({editArray});
  };

  render(){
    const { loading, userOption, expenseInfo, subsidyInfo } = this.props.params;
    const { submitLoading, expenseReportOID, hasUpdate, subsidyList, checkLoading, subsidyLength } = this.state;
    return(
      <div className='subsidy-content'>
        <section className='subsidy-content-form'>
        <Skeleton loading={loading}>
          {
            subsidyList.map((item, index) => {
              return (
                <SubsidyMiddle
                  subsidyObj={item}
                  key={index}
                  index={index}
                  changeHeader={() => this.setState({ hasUpdate: true })}
                  validateSave={this.validateSave}
                  deleteSubsidy={this.deleteSubsidy}
                  newOtherSubsidy={expenseInfo.newOtherSubsidy}
                  subsidyLength={subsidyLength}
                  userOption={userOption}
                  handleChange={this.handleChange}
                  expenseReportOID={expenseReportOID}
                  formOID={expenseInfo.formOID}
                  isWithTime={expenseInfo.withTime}
                  subsidyInfo={subsidyInfo}
                />
              );
            })
          }

          <If value={subsidyInfo.showExtend}>
            <Button type="dashed" className="button-add-subsidy" onClick={this.addSubsidy} loading={checkLoading}>
              {!checkLoading && <Icon type="plus"/>}
              {messages('expense-parent-report.key154')/*添加差旅行程*/}
            </Button>
          </If>
        </Skeleton>
        </section>
        <div className="footer-operate button-container">
          <Button type="primary" onClick={this.handleSave} className="button-save" loading={submitLoading}>
            {messages('common.save')/*保存*/}
          </Button>
          <Button onClick={() => this.props.close(hasUpdate)}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

export default connect()(SubsidyContent);
